#
# fusion.http.Admin
#
# Copyright 2007 Helsinki Institute for Information Technology
# and the authors.
#
# Authors: Ken Rimey <rimey@hiit.fi>
#

# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

'''
Handle the web root and URLs for which there is no other handler.

This handler is for the admin port.
'''

import web
import simplejson

from fusion.http.util import (
    withdb, format_xml,
    read_form, get_fields,
    authorized_referer, unauthorized)
from fusion.http.server import MAIN
from fusion.http.Default import Default
from fusion.http.Value import process_form
from fusion.http.Profile import profile_html

class Admin(Default):

    @withdb
    def GET_root(self, db):
        form = read_form()

        web.header('Content-Type', 'application/xhtml+xml; charset=UTF-8')

        print '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"'
        print '    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">'
        print '<html xmlns="http://www.w3.org/1999/xhtml">'
        print '<head><title>My Fusion Node</title></head>'
        print '<body>'

        print '<h1>My Fusion Node</h1>'

        if 'create_collection' in form:
            output_creation_interface(db, form)
        elif db.get_local_info('default_profile'):
            output_admin_interface(db)
        else:
            output_setup_interface(db)

        print '</body>'
        print '</html>'

    @withdb
    def POST(self, db, path):
        if path or not authorized_referer():
            return unauthorized()

        form = read_form()
        if 'init_profile' in form:
            name = form.getfirst('name', '')

            c = db.create_collection()

            db.put(c, 'info/title', name)
            db.put(c, 'info/type', 'tag:p2p-fusion,2007:profile')
            db.put(c, 'web/index.html', profile_html)

            profile = {
                'about': {'text': 'I have not yet filled out my profile.',
                          '_label': 'About Me'},
                }
            db.put(c, 'profile', simplejson.dumps(profile))

            db.set_local_info('default_profile', c)

            return web.seeother('/')
        elif 'create_collection' in form:
            c = db.create_collection()
            process_form(form, db, c)
            return web.seeother(MAIN + '/collection/' + c + '/web/index.html')

def output_admin_interface(db):
    start = db.get_start_collection()

    print '<ul>'

    print '<li>'
    url = MAIN + '/collection/' + start + '/web/index.html'
    print format_xml('a', 'Start Page', href=url)
    print '</li>'

    print '<li>'
    url = MAIN + '/profile/default'
    print format_xml('a', 'My Profile', href=url)
    print '</li>'

    print '<li>'
    url = '/collections/'
    print format_xml('a', 'Browse Database', href=url)
    print '</li>'

    print '</ul>'

def output_setup_interface(db):
    print '<p>'
    print 'Please enter a public name for yourself.'
    print 'It can be your full name, or just a first name or nickname.'
    print '<p></p>'
    print 'You can change it whenever you want.'
    print 'It is part of your <em>Profile</em>.'
    print '</p>'

    print '<form action="/" method="post">'
    print 'Name: '
    print format_xml('input', type='text', name='name')
    print format_xml('input', type='submit',
                     name='init_profile', value='Submit')
    print '</form>'

def output_creation_interface(db, form):
    print '<p>'
    print 'Please confirm that you want to create a new collection:'
    print '</p>'

    print '<form action="/" method="post">'
    for field_name in form:
        if ':' in field_name:
            for field in get_fields(form, field_name):
                print format_xml('input', type='hidden', name=field_name, value=field.value)
    print format_xml('input', type='submit',
                     name='create_collection', value='Confirm')
    print format_xml('input', type='submit', value='Cancel',
                     onclick='window.location="/"; return false;')
    print '</form>'

    print '<hr/>'

    print '<dl>'
    for field_name in form:
        if ':' in field_name:
            for field in get_fields(form, field_name):
                print format_xml('dt', field_name + ':')
                print '<dd>' + format_xml('pre', field.value) + '</dd>'
    print '</dl>'
